/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package es.edn.pecera.client.comms;

import java.io.InterruptedIOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 *
 * @author jorge
 */
public class ServerListener implements Runnable {

    /**
     * Log.
     */
    private final Log log = LogFactory.getLog(ServerListener.class);
    /**
     * Servidor.
     */
    private DatagramSocket server = null;
    /**
     * Puerto.
     * Valor por defecto: 6666.
     */
    private int port = 6666;

    /**
     * Establece el puerto.
     * @param port un puerto.
     */
    public void setPort(int port) {
        this.port = port;
    }
    /**
     * Interface por el que escuchar.
     */
    private String iface = null;

    /**
     * Establece el interface por el que escuchar.
     * Si no se establece ninguno se utiliza el por defecto del sistema.
     * @param iface una direccion valida de un interface local.
     */
    public void setInterface(String iface) {
        this.iface = iface;
    }
    /**
     * Escuchador de notificaciones.
     */
    private NotificationListener listener = null;

    /**
     * Establece el escuchador de notificaciones.
     * @param listener un escuchador de notificaciones.
     */
    public void setNotificationListener(NotificationListener listener) {
        this.listener = listener;
    }
    /**
     * Indica si el servidor estÃ¡ parado.
     * true si estÃ¡ parado, false si no lo estÃ¡.
     * Valor por defecto: true.
     */
    private volatile boolean isServerStopped = true;

    public void start() throws Exception {
        if (isRunning()) {
            log.info("UDP server is already running");
        } else {
            try {
                if (iface == null || iface.trim().length() == 0) {
                    server = new DatagramSocket(port);
                } else {
                    server = new DatagramSocket(port, InetAddress.getByName(iface));
                }
                server.setSoTimeout(10 * 1000);
                log.info("UDP server listening port " + server.getLocalPort());
                isServerStopped = false;
                final Thread thread = new Thread(this);
                thread.start();
            } catch (Exception e) {
                log.fatal("Cannot start UDP server", e);
                isServerStopped = true;
                throw e;
            }
        }
    }

    public synchronized void shutdown() {
        if (isRunning()) {
            if (isServerStopped) {
                log.info("UDP server is already being shut down.");
            } else {
                isServerStopped = true;
                try {
                    byte[] buf = "".getBytes();
                    DatagramPacket packet = new DatagramPacket(buf, buf.length, InetAddress.getLocalHost(), port);
                    DatagramSocket udp = new DatagramSocket();
                    udp.send(packet);
                    log.info("Shutting down UDP server");
                } catch (Exception ex) {
                    Logger.getLogger(ServerListener.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        } else {
            log.info("UDP server is not running");
        }
    }

    public void run() {
        try {
            while (!isServerStopped) {
                try {
                    log.debug("UDP server listening");
                    final byte[] buff = new byte[100];
                    final DatagramPacket packet = new DatagramPacket(buff, buff.length);
                    if (buff.length > 0) {
                        server.receive(packet);
                        final byte[] received = new byte[packet.getLength()];
                        System.arraycopy(packet.getData(), 0, received, 0, received.length);
                        final Runnable runnable = new Runnable() {

                            public void run() {
                                listener.onUIDReceived(packet.getAddress().getHostAddress(), received);
                            }
                        };
                        final Thread thread = new Thread(runnable);
                        thread.start();
                    }
                } catch (InterruptedIOException iioe) {
                    log.debug("Resetting UDP server");
                }
            }
        } catch (Exception e) {
            log.fatal("Cannot run UDP server", e);
            isServerStopped = true;
        }
    }

    public boolean isRunning() {
        if (isServerStopped && (listener.getQueuedFilesCount() == 0)) {
            return false;
        }
        return true;
    }
}
